/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-03-12 11:55:23
 * @LastEditors: DESKTOP-05FP536\Administrator 18368095041@163.com
 * @LastEditTime: 2025-02-02 22:24:29
 * @FilePath: \vue3-admin\src\service\useLogin.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { ref } from 'vue';
import {
    login,
    LoginParam,
    logout as logoutApi,
    generateCaptchaUrl
} from '@/api/login';
import { useUserStore } from '@/store';
import { message } from '@/utils';

export { LoginParam };

export const useLogin = () => {
    const userStore = useUserStore();

    const loading = ref(false);
    const token = ref('');
    /**
     * 账号密码登录
     * @param param
     * @returns
     */
    const loginByPassword = (param: LoginParam) => {
        if (loading.value) return;
        loading.value = true;
        return login(param)
            .then((res) => {
                token.value = res.data;
                userStore.setToken(res.data);
                return res;
            })
            .finally(() => {
                loading.value = false;
            });
    };

    const logoutLoading = ref(false);
    /**
     * 服务器登出
     * @returns
     */
    const serverLogout = () => {
        if (logoutLoading.value) return;
        logoutLoading.value = true;
        return logoutApi().finally(() => {
            logoutLoading.value = false;
        });
    };

    /**
     * 登出
     */
    const logout = async () => {
        try {
            await serverLogout();
            userStore.fedLogout();
        } catch (e) {
            message('登出错误', 'error');
            console.log(e);
        }
    };

    return {
        loading,
        loginByPassword,
        logoutLoading,
        serverLogout,
        generateCaptchaUrl,
        logout
    };
};
